const app = getApp();
Page({
    data: {
        userId: "",
        qualityMap: {
            1: "精品",
            2: "次品",
            3: "统货"
        },
        showBookPicker: false,
        intFlag: false,
        printFlag: false,
        bookList: [],
        syncOrderItem: {},
        allChecked: false,
        showPriceConfirm: false,
        selectedOrderList: [],
        priceInfo: {},
        orderList: [],
        show: false,
        startTime: "",
        endTime: "",
        minDate: new Date(2021, 0, 1).getTime(),
        maxDate: new Date().getTime(),
    },
    onLoad: function (options) {
        this.setData({
            userId: options.id,
        })
        wx.setNavigationBarTitle({
            title: options.title
        })
        this.getData()
        this.getBookData()
    },
    resetData: function () {
        this.setData({
            showBookPicker: false,
            intFlag: false,
            printFlag: false,
            allChecked: false,
            startTime: "",
            endTime: "",
            showPriceConfirm: false,
            selectedOrderList: [],
            priceInfo: {},
            orderList: []
        })
    },
    onDisplay() {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    onConfirm(event) {
        this.resetData();
        const [start, end] = event.detail;
        this.setData({
            show: false,
            startTime: this.formatDate(start),
            endTime: this.formatDate(end)
        });
        this.getData();
    },
    formatDate(date = new Date()) {
        return wx.$dayjs(date).format("YYYY/MM/DD");
    },
    onPullDownRefresh() {
        this.resetData()
        this.getData()
    },
    getData: function () {
        const {
            startTime,
            endTime
        } = this.data;
        let createStartTime = startTime ? wx.$dayjs(startTime).format("YYYY-MM-DD") + " 00:00:00" : "";
        let createEndTime = endTime ? wx.$dayjs(endTime).format("YYYY-MM-DD") + " 23:59:59" : "";
        let params = {
            current: 1,
            size: 100,
            createStartTime,
            createEndTime,
            enterStockStatus: 3,
            companyId: app.globalData.userInfo.companyData.companyId,
            farmerUserId: this.data.userId
        }
        wx.showLoading({
            title: "正在请求数据中"
        })
        wx.$apis.getMarketList(params).then(res => {
            wx.stopPullDownRefresh();
            let orderList = res.data && res.data.records.map(item => {
                item.createTimeStr = item.createTime && item.createTime.replace("T", " ")
                item.countPrice = item.countPrice && wx.$getYuan(item.countPrice)
                item.managementFee = item.managementFee && wx.$getYuan(item.managementFee)
                item.transactionPrice = item.transactionPrice && wx.$getYuan(item.transactionPrice)
                return item
            })
            this.setData({
                orderList: orderList
            })
        })
    },
    getBookData() {
        wx.$apis.getAccountBookEasy().then(res => {
            let bookList = res.data && res.data.map(item => {
                item.text = item.name
                return item
            })
            this.setData({
                bookList: bookList
            })
        })
    },
    syncToAccountBook(e) {
        let item = e.currentTarget.dataset.item
        this.setData({
            syncOrderItem: item,
            showBookPicker: true
        })
    },
    onBookCancel() {
        this.setData({
            syncOrderItem: {},
            showBookPicker: false
        })
    },
    onBookConfirm(event) {
        const {
            value
        } = event.detail;
        let params = {
            accountBookId: value.id,
            financeName: "买菜",
            recordTime: wx.$dayjs().format("YYYY-MM-DD HH:mm:ss"),
            orderType: 2,
            orderId: this.data.syncOrderItem.id,
            type: 1,
        }
        wx.showLoading({
            title: "正在同步"
        })
        wx.$apis.addAccountBookRecord(params).then(res => {
            this.setData({
                showBookPicker: false
            })
            wx.showToast({
                title: '同步完成！',
                icon: 'success',
                duration: 1500
            })
            this.resetData()
            this.getData()
        })
    },
    onChange: function (event) {
        let index = event.currentTarget.dataset.index
        let orderList = this.data.orderList;
        orderList[index].checked = !orderList[index].checked
        let allChecked = true;
        if (orderList && orderList.length) {
            orderList.forEach(item => {
                if (!item.checked) {
                    allChecked = false
                }
            });
        } else {
            allChecked = false
        }
        let selectedOrderList = orderList.filter(item => item.checked)
        this.setData({
            orderList: orderList,
            selectedOrderList: selectedOrderList,
            allChecked: allChecked
        })
        this.getPriceInfo()
    },
    checkAll: function (event) {
        let orderList = this.data.orderList;
        if (event.detail) {
            orderList.forEach(item => {
                item.checked = true
            });
        } else {
            orderList.forEach(item => {
                item.checked = false
            });
        }
        let selectedOrderList = orderList.filter(item => item.checked)
        this.setData({
            orderList: orderList,
            selectedOrderList: selectedOrderList,
            allChecked: event.detail
        });
        this.getPriceInfo()
    },
    setActualPayment: function (event) {
        let settlementAmount = this.data.priceInfo.settlementAmount
        if (event.detail) {
            this.setData({
                'priceInfo.actualPayment': Math.floor(settlementAmount),
                'intFlag': true
            })
        } else {
            this.setData({
                'priceInfo.actualPayment': settlementAmount,
                'intFlag': false
            })
        }
    },
    setPrint: function (event) {
        this.setData({
            printFlag: event.detail
        })
    },
    getPriceInfo() {
        let selectedOrderList = this.data.selectedOrderList;
        if (selectedOrderList && selectedOrderList.length) {
            let settlementAmount = 0;
            selectedOrderList.forEach(item => {
                settlementAmount += item.countPrice
            });
            let priceInfo = {
                companyName: selectedOrderList[0].companyName,
                farmerName: selectedOrderList[0].farmerName,
                farmerMobile: selectedOrderList[0].farmerMobile,
                settlementAmount: settlementAmount,
                actualPayment: settlementAmount,
                orderNumber: selectedOrderList.length
            }
            this.setData({
                priceInfo: priceInfo,
            })
        } else {
            this.setData({
                priceInfo: {}
            })
        }
    },
    pay() {
        let selectedOrderList = this.data.selectedOrderList;
        if (selectedOrderList && selectedOrderList.length) {
            this.setData({
                showPriceConfirm: true,
            })
        } else {
            wx.showToast({
                title: "请勾选订单",
                icon: 'none',
                duration: 2000
            })
        }
    },
    hideConfirm() {
        this.setData({
            showPriceConfirm: false
        })
    },
    submitConfirm() {
        const {
            printFlag
        } = this.data;
        let orderIds = this.data.selectedOrderList.map(item => item.id)
        let params = {
            printFlag: printFlag,
            companyId: app.globalData.userInfo.companyData.companyId,
            orderIds: orderIds,
            userId: this.data.userId,
            settlementAmount: Math.round(this.data.priceInfo.settlementAmount * 100),
            actualPayment: Math.round(this.data.priceInfo.actualPayment * 100),
        }
        wx.showLoading({
            title: "正在请求数据中"
        })
        wx.$apis.settlement(params).then(res => {
            wx.setStorage({
                key: "back",
                data: true,
                success: function () {
                    wx.navigateBack(); //返回上一个页面
                }
            })
        })
    },
})